<?php
class Authentification{
	private $db, $table;
	private $user, $passwd, $id, $mail, $domain, $loggedIn;


	function __construct($db, $table){
		Session::start();
		$this->db = $db;
		$this->table = $table;
		$this->log = new Logger("Auth\t", _LOGPATH_);
		$this->log->setLogLevel(Logger::VERBOSE);
	}

	public function create($user, $passwd, $group, $mail, $domain){
		$this->db->insert("INSERT INTO user (user, passwd, usergroup, mail, domain) VALUES ('%s', '%s', '%s', '%s', '%s')",
		$user, md5(_SALT_.$passwd), $group, $mail, $domain
		);
	}

	private function login($user, $passwd){
		$this->loggedIn = false;
		$this->log->debug("Trying to login with $user, $passwd");
		$this->user = $user;
		$this->passwd = $passwd;
		$selection = $this->db->select("SELECT user, id FROM $this->table WHERE user='%s' AND pwd='%s'",$this->user,md5(_SALT_.sha1($this->passwd)));
		$numOfRows = $selection->getRowNum();
		if($numOfRows == 1){
			$result = $selection->getRow();
			$this->user = $result[0];
			$this->id = $result[1];
			Session::set("user",$this->user);
			Session::set("passwd",$this->passwd);
			$this->loggedIn = true;
			$this->log->verbose("Login successful");
			return true;
		}else{
			$this->log->warning("Login failed!");
		}
		return false;
	}

	public function manualLogin($user, $passwd){
		Session::newID();
		return $this->login($user, $passwd);
	}

	public function sessionLogin(){
		if(Session::check() && Session::exists('user') && Session::exists('passwd')){
			return $this->login(Session::get('user') ,Session::get('passwd'));
		}
		return false;
	}

	public function getLoginStatus(){
		return $this->loggedIn;
	}

	public function logout(){
		session_unset();
		session_destroy();
	}

	public function getUser(){
		return $this->user;
	}

	public function getID(){
		return $this->id;
	}

	public function isSecure(){
		return $this->loggedIn;
	}
}